import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getTimeStamp } from '@/utils/auth'
// create an axios instance
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  //timeout: 10000 // request timeout
})

// request interceptor
request.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = store.getters.token
    if (token) {
      if (isTimeout()) {
        store.dispatch('user/userlogout')
        router.push('/login')
        return Promise.reject(new Error('登录过期'))
      }
      config.headers.Authorization = ` ${token}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(
  response => {
    // 解构一层data
    const { data } = response
    if (response.data.code) {
      if (response.data.code !== 200) {
        Message({
          type: 'error',
          message: response.data.msg || 'Error'
        })
      }
    }
    return data
  },
  error => {
    console.log('err' + error)
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
const timeout = 43200
const isTimeout = () => {
  const currentTime = Date.now()
  const timeStamp = getTimeStamp()
  return (currentTime - timeStamp) / 1000 > timeout
}

export default request
